﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Story2dLogic : MonoBehaviour
{
    public GameObject storyObj;

    public string storyId;
    public bool isStoryStart = false;
    public float curDeltaTime;

    StoryEndCallback endCallback = null;

    float duration;
    string backgroundMusic;

    List<StorySoundInfo> allSoundInfo = new List<StorySoundInfo>();
    Queue<StorySoundInfo> soundInfo;
    StorySoundInfo currentSoundInfo;

    List<StorySubtitleInfo> subTitleInfo = new List<StorySubtitleInfo>();
    StorySubtitleInfo curSubtitle = null;

    public IEnumerator LoadResource()
    {
        int taskCount = 0;
        foreach (var audio in allSoundInfo)
        {
            StartCoroutine(AudioManager.Instance.LoadAudioResource(audio.audioName, () => { taskCount--; }));
            taskCount++;
        }

        while(taskCount > 0)
        {
            yield return null;
        }

        isStoryStart = true;
        curDeltaTime = 0f;
        storyObj.SetActive(true);
    }

    public void UnloadResource()
    {
        foreach (var audio in allSoundInfo)
        {
            AudioManager.Instance.UnloadAudioResource(audio.audioName);
        }
    }

    public void SetStoryEndCallback(StoryEndCallback callback)
    {
        endCallback = callback;
    }

    public void StoryStart()
    {
        var dict = Dict.Blo.Dict2dStoryBlo.GetTable2dStory(storyId);
        if (dict != null)
        {
            duration = (float)dict.StoryDuration;
            backgroundMusic = dict.StoryMusic;
            ParseStorySoundInfo(dict.StorySound);
            ParseStorySubtitle(dict.StorySubtitle);
            if (!string.IsNullOrEmpty(backgroundMusic))
            {
                AudioManager.Instance.PlayBackgroundMusic(backgroundMusic);
            }
            StartCoroutine(LoadResource());
        }
        else
        {
            Debug.LogError("StoryId:" + storyId + " not exit in dict!!");
        }
    }

    void Update()
    {
        if (isStoryStart)
        {
            curDeltaTime += Time.deltaTime;
            if (currentSoundInfo == null)
            {
                if (soundInfo.Count > 0)
                {
                    currentSoundInfo = soundInfo.Dequeue();
                }
            }
            if (currentSoundInfo != null)
            {
                if (currentSoundInfo.time <= curDeltaTime)
                {
                    AudioManager.Instance.PlaySingle(currentSoundInfo.audioName);
                    currentSoundInfo = null;
                }
            }
            if (curSubtitle == null)
            {
                foreach(var t in subTitleInfo)
                {
                    if (curDeltaTime >= t.startTime && curDeltaTime <= t.stopTime)
                    {
                        curSubtitle = t;
                        break;
                    }
                }
            }
            if (curSubtitle!= null)
            {
                if (curDeltaTime >= curSubtitle.startTime && curDeltaTime <= curSubtitle.stopTime)
                {
                    ShowText(curSubtitle.text);
                }
                else
                {
                    HideText();
                    curSubtitle = null;
                }
            }

            if (curDeltaTime >= duration)
            {
                StoryEnd();
            }
        }

    }

    void ShowText(string text)
    {
        //SubTitlePanel.Instance.Show();
        //SubTitlePanel.Instance.SetText(text);
    }

    void HideText()
    {
        //SubTitlePanel.Instance.Hide();
    }

    public void StoryEnd()
    {
        UnloadResource();
        if (endCallback != null)
        {
            endCallback();
        }
        isStoryStart = false;
        storyObj.SetActive(false);
    }

    void ParseStorySoundInfo(string infoStr)
    {
        var arr = infoStr.Split(new char[1] { '#' }, System.StringSplitOptions.RemoveEmptyEntries);
        allSoundInfo = new List<StorySoundInfo>();
        foreach (var info in arr)
        {
            var arr0 = info.Split(new char[1] { '=' }, System.StringSplitOptions.RemoveEmptyEntries);
            if (arr0.Length == 2)
            {
                float time = float.Parse(arr0[1]);
                string name = arr0[0];
                StorySoundInfo clip = new StorySoundInfo(name, time);
                allSoundInfo.Add(clip);
            }
        }
        allSoundInfo.Sort(delegate (StorySoundInfo x, StorySoundInfo y)
        {
            return x.time.CompareTo(y.time);
        });
        soundInfo = new Queue<StorySoundInfo>();
        foreach (var info in allSoundInfo)
        {
            soundInfo.Enqueue(info);
        }
        currentSoundInfo = null;
    }

    void ParseStorySubtitle(string infoStr)
    {
        var arr = infoStr.Split(new char[1] { '#' }, System.StringSplitOptions.RemoveEmptyEntries);
        List<StorySubtitleInfo> list = new List<StorySubtitleInfo>();
        foreach (var info in arr)
        {
            var arr0 = info.Split(new char[1] { '=' }, System.StringSplitOptions.RemoveEmptyEntries);
            if (arr0.Length == 2)
            {
                string text = TableTextBlo.GetText(arr0[1]);
                var arr1 = arr0[0].Split(new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
                if (arr1.Length == 2)
                {
                    float startTime = float.Parse(arr1[0]);
                    float stopTime = float.Parse(arr1[1]);
                    StorySubtitleInfo subTitle = new StorySubtitleInfo(startTime, stopTime, text);
                    list.Add(subTitle);
                }
            }
        }
        list.Sort(delegate (StorySubtitleInfo x, StorySubtitleInfo y)
        {
            return x.startTime.CompareTo(y.startTime);
        });
        subTitleInfo = list;
    }


}